<template>
  <div class="wrap">
    <h2>订阅中心</h2>

    <!-- 当前订阅 -->
    <section class="card current" v-if="current">
      <div class="row">
        <div>
          <div class="muted">当前套餐</div>
          <div class="big">{{ snapshot?.name || ('#' + current.planId) }}</div>
        </div>
        <div>
          <div class="muted">有效期</div>
          <div>{{ fmtDatetime(current.startTime) }} ~ {{ fmtDatetime(current.endTime) }}</div>
        </div>
        <div>
          <div class="muted">状态</div>
          <div class="tag green">{{ current.status }}</div>
        </div>
      </div>

      <div class="features" v-if="snapshot">
        <span v-if="snapshot.maxMailAccounts!=null">可绑定邮箱：{{ snapshot.maxMailAccounts }}</span>
        <span v-if="snapshot.outboundLimitPerPeriod!=null">周期外发上限：{{ snapshot.outboundLimitPerPeriod }}</span>
        <span v-if="snapshot.allowChatGPT">支持 ChatGPT</span>
        <span v-if="snapshot.allowDeepSeek">支持 DeepSeek</span>
        <span v-if="snapshot.allowDualChain">多模型级联</span>
      </div>

      <div class="actions">
        <button v-if="!current.autoRenew" class="btn" @click="toggleAutoRenew(true)" :disabled="busy">
          开启自动续订
        </button>
        <button v-else class="btn outline" @click="toggleAutoRenew(false)" :disabled="busy">
          关闭自动续订
        </button>
      </div>
    </section>

    <!-- 计划列表 -->
    <section>
      <h3>可选套餐</h3>
      <div class="grid">
        <div class="plan" v-for="p in plans" :key="p.id">
          <div class="plan-hd">
            <div class="plan-name">{{ p.name }}</div>
            <div class="plan-price">
              <span class="yen">¥</span>{{ centsToYuan(p.priceCents) }}
              <span class="per">/ {{ periodLabel(p.period) }}</span>
            </div>
          </div>

          <ul class="plan-features">
            <li v-if="p.maxMailAccounts!=null">可绑定邮箱 {{ p.maxMailAccounts }}</li>
            <li v-if="p.outboundLimitPerPeriod!=null">周期外发上限 {{ p.outboundLimitPerPeriod }}</li>
            <li v-if="p.allowChatGPT">支持 ChatGPT</li>
            <li v-if="p.allowDeepSeek">支持 DeepSeek</li>
            <li v-if="p.allowDualChain">支持多模型级联</li>
          </ul>

          <div class="selects">
            <label>计费周期</label>
            <select v-model="selectedPeriod[p.id]" class="select">
              <option :value="p.period">{{ periodLabel(p.period) }}（按套餐默认）</option>
              <option v-for="opt in allPeriods"
                      :key="opt"
                      :value="opt"
                      v-show="opt!==p.period">
                {{ periodLabel(opt) }}
              </option>
            </select>
          </div>

          <button class="btn block"
                  :disabled="buyingId===p.id || busy"
                  @click="buy(p)">
            {{ buyingId===p.id ? '跳转支付宝…' : '购买' }}
          </button>
        </div>
      </div>
    </section>

    <p v-if="error" class="err">{{ error }}</p>
  </div>
</template>

<script>
export default { name: 'AccountSubscription' }
</script>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { accountApi  } from '@/api/account'

const plans = ref([])
const current = ref(null)
const snapshot = computed(() => {
  // planSnapshotJson 是后端保存的字符串快照
  try { return current.value?.planSnapshotJson ? JSON.parse(current.value.planSnapshotJson) : null } catch { return null }
})

const error = ref('')
const busy = ref(false)
const buyingId = ref(null)
const selectedPeriod = reactive({}) // per planId

const allPeriods = ['MONTHLY', 'QUARTERLY', 'YEARLY']

onMounted(async () => {
  await refresh()
})

async function refresh() {
  error.value = ''
  try {
    const [ps, cur] = await Promise.all([
      accountApi.listPlans(),
      accountApi.getCurrentSub()
    ])

    // 既兼容“返回 data 包装的响应”，也兼容“直接返回 data”
    const plansData = Array.isArray(ps?.data) ? ps.data : (Array.isArray(ps) ? ps : [])
    const curData = (cur && typeof cur === 'object' && 'data' in cur) ? cur.data : cur

    plans.value = plansData || []
    current.value = curData || null

    // 方便你调试
    console.log('[Sub] plans.length=', plans.value.length, ' current=', current.value)

    // 默认选中各计划的周期
    for (const p of plans.value) {
      if (!(p.id in selectedPeriod)) selectedPeriod[p.id] = p.period
    }
  } catch (e) {
    console.error('[Sub] /plans or /current error:', e?.response || e)
    const msg = e?.response?.data?.message
        || (e?.response?.status ? `HTTP ${e.response.status}` : '')
        || '加载失败'
    error.value = msg
  }
}


function periodLabel(p) {
  switch (p) {
    case 'MONTHLY': return '按月'
    case 'QUARTERLY': return '按季'
    case 'YEARLY': return '按年'
    default: return p
  }
}

function centsToYuan(cents) {
  if (cents == null) return '0.00'
  return (cents / 100).toFixed(2)
}

function fmtDatetime(s) {
  if (!s) return '-'
  // s 可能是 "2025-08-23T12:34:56" / "2025-08-23 12:34:56"
  return String(s).replace('T', ' ')
}

async function buy(p) {
  error.value = ''
  busy.value = true
  buyingId.value = p.id
  try {
    const period = selectedPeriod[p.id] || p.period
    const resp = await accountApi.purchasePlan(p.id, period, `购买-${p.name}`)
    const payload = (resp && typeof resp === 'object' && 'data' in resp) ? resp.data : resp
    const url = payload?.payUrl
    if (!url) {
      console.warn('[Sub] purchase resp (no payUrl):', resp)
      throw new Error('未返回支付地址')
    }
    window.location.href = url
  } catch (e) {
    error.value = e?.response?.data?.message || e.message || '下单失败'
  } finally {
    busy.value = false
    buyingId.value = null
  }
}

async function toggleAutoRenew(enable) {
  error.value = ''
  busy.value = true
  try {
    if (enable) await accountApi.enableAutoRenew()
    else await await accountApi.cancelAutoRenew()
    await refresh()
  } catch (e) {
    error.value = e?.response?.data?.message || '操作失败'
  } finally {
    busy.value = false
  }
}
</script>

<style scoped>
.wrap { max-width: 1000px; margin: 24px auto; padding: 0 16px; }
h2 { margin: 8px 0 16px; }
h3 { margin: 16px 0 8px; }

.card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 14px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0,0,0,.04);
}
.row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; align-items: start; }
.muted { color: #6b7280; font-size: 12px; }
.big { font-weight: 600; font-size: 18px; }
.tag { padding: 4px 8px; border-radius: 999px; font-size: 12px; }
.tag.green { background: #ecfdf5; color: #047857; }

.features { display: flex; flex-wrap: wrap; gap: 8px 12px; margin-top: 12px; color: #374151; }
.features span { background: #f3f4f6; border-radius: 999px; padding: 4px 10px; font-size: 12px; }

.actions { margin-top: 12px; }

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
}
.plan {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  background: #fff;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.plan-hd { display: flex; align-items: baseline; justify-content: space-between; }
.plan-name { font-weight: 600; }
.plan-price { font-size: 22px; font-weight: 700; }
.plan-price .yen { font-size: 14px; margin-right: 2px; }
.plan-price .per { font-size: 12px; font-weight: 400; color:#6b7280; margin-left: 6px; }
.plan-features { margin: 0; padding-left: 18px; color:#374151; min-height: 60px; }
.selects { display: grid; gap: 6px; }
.select { border: 1px solid #e5e7eb; border-radius: 8px; padding: 8px 10px; background: #fff; }

.btn {
  display: inline-block;
  padding: 10px 14px;
  border-radius: 10px;
  border: 1px solid #111827;
  background: #111827;
  color: #fff;
  cursor: pointer;
}
.btn.block { width: 100%; text-align: center; }
.btn.outline { background: #fff; color:#111827; border-color:#111827; }
.btn:disabled { opacity: .6; cursor: not-allowed; }

.err { color: #b91c1c; margin-top: 12px; }
</style>
